import {ref} from "vue";
import {getSearchList} from "../../api/mock/mock.js";
/**
 * 上拉刷新和下拉加载更多hooks
 * @type {Ref<UnwrapRef<*[]>>}
 */
export const useLoad = () => {
    const list = ref([]);
    const loading = ref(false);
    const finished = ref(false);
    const refreshing = ref(false);

    const onLoad = () => {
        // 异步更新数据
        // setTimeout 仅做示例，真实场景中一般为 ajax 请求
        setTimeout(async () => {
            if (refreshing.value) {
                list.value = [];
                refreshing.value = false;
            }
            const data = await getSearchList()

            // for (let i = 0; i < 10; i++) {
                // list.value.push(list.value.length + 1);
                // finished.value = true;
            // }
            list.value = list.value.concat(data)
            console.log('loading' + Math.random(),data)

            // 加载状态结束
            loading.value = false;

            // 数据全部加载完成
            if (list.value.length >= 40) {
                // finished.value = true;
            }
        }, 600);
    };
    const onRefresh = () => {
        // 清空列表数据
        finished.value = false;
        // 重新加载数据
        // 将 loading 设置为 true，表示处于加载状态
        loading.value = true;
        onLoad()
    };

    return {
        list, loading, finished, refreshing, onLoad, onRefresh
    }
}